﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLLottery.Common;
using System.Collections.ObjectModel;
using SLLottery.LotterySrv;
using System.Windows.Threading;

namespace SLLottery
{
    public partial class MoneyWindow : ChildWindow
    {
        private LotterySrv.LotteryServiceClient srv;
        User user = (User)App.Session[Constant.USERINFO_SESSION];
        private DispatcherTimer timerShowInvalidTime;
        private DateTime invalidTime;
        double moneyOut;
        public int WaitCount = -1;
        private static int selectedIndex = 0;
        public MoneyWindow()
        {
            InitializeComponent();
            srv = WcfProxy.GetProxy;
            srv.ValidateBankPasswordCompleted += new EventHandler<ValidateBankPasswordCompletedEventArgs>(srv_ValidateBankPasswordCompleted);
            srv.GetCarrierBankInfoCompleted += new EventHandler<GetCarrierBankInfoCompletedEventArgs>(srv_GetCarrierBankInfoCompleted);
            srv.GetCapitalInfoCompleted += new EventHandler<GetCapitalInfoCompletedEventArgs>(srv_GetCapitalInfoCompleted);
            this.lbMinMoney.Text = string.Format("最小提现金额{0}元", Constant.MinOutMoneyOneTime);
            this.lbMoneyTimes.Text = string.Format("每日提现最多{0}次,最多{1}元", Constant.MaxOutMoneyTimesOneDay, Constant.MaxOutMoneyOneDay);
            srv.GetCarrierBankInfoCompleted += new EventHandler<GetCarrierBankInfoCompletedEventArgs>(srv_GetCarrierBankInfoCompleted);
            timerShowInvalidTime = new DispatcherTimer();
            timerShowInvalidTime.Tick += new EventHandler(timerShowInvalidTime_Tick);
            rbtMoneyOut.IsChecked = true;
        }

        void srv_GetCapitalInfoCompleted(object sender, GetCapitalInfoCompletedEventArgs e)
        {
            Capital cp = e.Result;
            if (e.Result == null)
            {
                Messager.Show("账号异常请重新登录，如果再次出现该问题请联系管理员!");
                App.Navigation(new LoginPage());
            }
            if (cp.EnableScores < moneyOut)
            {
                gridLoading.Visibility = Visibility.Collapsed;
                Messager.Show("你的账户可用资金已经不足提现金额!");
                return;
            }
            gridLoading.Visibility = Visibility.Visible;
            LotteryServiceClient client = WcfProxy.GetProxy;
            client.ApplyMoneyOutAsync(user.UserId, moneyOut, Constant.MaxOutMoneyOneDay, Constant.MaxOutMoneyTimesOneDay,cbx_bankType_out.SelectedValue.ToString());
            client.ApplyMoneyOutCompleted += (se, ea) =>
            {
                gridLoading.Visibility = Visibility.Collapsed;
                if (ea.Result == -3)
                    Messager.Show("网络故障或者服务器异常,请稍后再试!");
                else if (ea.Result == -1)
                    Messager.Show(string.Format("每天最多提现{0}次", Constant.MaxOutMoneyTimesOneDay));
                else if (ea.Result == -2)
                    Messager.Show(string.Format("每天最多提现{0}元", Constant.MaxOutMoneyOneDay));
                else
                {
                    Messager.Show("提现申请已提交,请注意查收！");
                    WaitCount = ea.Result;
                }

            };

        }

        void timerShowInvalidTime_Tick(object sender, EventArgs e)
        {
            TimeSpan span = (TimeSpan)(this.invalidTime - DateTime.Now);
            if (span.TotalSeconds < 1.0)
            {
                this.timerShowInvalidTime.Stop();
            }
            this.lbValidTime.Text=span.ToString("mm") + ":" + span.ToString("ss");
        }

        void srv_GetCarrierBankInfoCompleted(object sender, GetCarrierBankInfoCompletedEventArgs e)
        {
            gridLoading.Visibility = Visibility.Collapsed;
            if (e.Result.Count==0)
            {
                gridInValid.Visibility = Visibility.Visible;
            }
            else
            {
                cbx_bankType_in.Tag = e.Result.ToList();
                cbx_bankType_in.DisplayMemberPath = "BankType";
                cbx_bankType_in.SelectedValuePath = "BankType";
                cbx_bankType_in.ItemsSource = e.Result.ToList();
                if (e.Result.Count - 1 >= selectedIndex)
                    cbx_bankType_in.SelectedIndex = selectedIndex;
                else
                    cbx_bankType_in.SelectedIndex = 0;
            }
        }
        void srv_ValidateBankPasswordCompleted(object sender, ValidateBankPasswordCompletedEventArgs e)
        {
            if (e.Result)
            {
                srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
            }
            else
            {
                gridLoading.Visibility = Visibility.Collapsed;
                Messager.Show("资金密码错误！");
            }
            
        }
        private void BindBankInfo()
        {
            srv.GetBankInfoAsync(user.UserId);
            srv.GetBankInfoCompleted += new EventHandler<GetBankInfoCompletedEventArgs>(srv_GetBankInfoCompleted);
        }
        private void BindCarrierBankInfo()
        {
            srv.GetCarrierBankInfoAsync();
            gridLoading.Visibility = Visibility.Visible;

        }
        void srv_GetBankInfoCompleted(object sender, GetBankInfoCompletedEventArgs e)
        {
            gridLoading.Visibility = Visibility.Collapsed;
            if (e.Result.Count> 0)
            {
                cbx_bankType_out.Tag = e.Result.ToList();
                cbx_bankType_out.SelectedValuePath = "BankType";
                cbx_bankType_out.DisplayMemberPath = "BankType";
                cbx_bankType_out.ItemsSource = e.Result.ToList();
                cbx_bankType_out.SelectedIndex = 0;
                btOk.IsEnabled = true;
            }
            else
            {
                lbErrorMsg.Text = "尚未设置银行资料,无法提现！";
            }
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void rbtMoneyOut_Checked(object sender, RoutedEventArgs e)
        {
            BindBankInfo();
            gridMoneyIn.Visibility = Visibility.Collapsed;
            spRefresh.Visibility = Visibility.Collapsed;
            gridMoneyOut.Visibility = Visibility.Visible;
        }

        private void rbtMoneyIn_Checked(object sender, RoutedEventArgs e)
        {
            selectedIndex = 0;
            //BindCarrierBankInfo();
            gridMoneyIn.Visibility = Visibility.Visible;
            gridMoneyOut.Visibility = Visibility.Collapsed;
            spRefresh.Visibility = Visibility.Visible;
            btRefresh_Click(this,null);
        }

        private void btOk_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tbAmount.Text.Trim()) || string.IsNullOrEmpty(tbPassword.Password.Trim()))
            {
                Messager.Show("金额或者资金密码不能为空！");
                return;
            }

            if (!double.TryParse(tbAmount.Text.Trim(), out moneyOut))
            {
                Messager.Show("金额为数字！");
                return;
            }
            if (moneyOut > Constant.MaxOutMoneyOneTime || moneyOut<Constant.MinOutMoneyOneTime)
            {
                Messager.Show(string.Format("每次提现范围:{0}-{1}！", Constant.MinOutMoneyOneTime, Constant.MaxOutMoneyOneTime));
                return;
            }
            srv.ValidateBankPasswordAsync(user.UserId, tbPassword.Password.Trim());
            gridLoading.Visibility = Visibility.Visible;
        }

        private void lbMoneyInDemo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MoneyInDemoWindow md = new MoneyInDemoWindow();
            md.ShowWindow(cbx_bankType_in.SelectedValue.ToString());
        }

        private void lbCopyBankAccount_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Clipboard.SetText(this.lbBankAccount.Text);
        }

        private void lbCopyUserId_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Clipboard.SetText(this.lbUserId.Text);
        }

        private void lbCopyAccountName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Clipboard.SetText(this.lbAccountName.Text);
        }

        private void btRefresh_Click(object sender, RoutedEventArgs e)
        {
            timerShowInvalidTime.Stop();
            gridLoading.Visibility = Visibility.Visible;
            selectedIndex = cbx_bankType_in.SelectedIndex == -1 ? 0 : cbx_bankType_in.SelectedIndex;
            BindCarrierBankInfo();
        }

        private void cbx_bankType_out_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cbx = sender as ComboBox;
            if (cbx.Tag != null && cbx.SelectedValue != null)
            {
                List<BankInfo> list = cbx.Tag as List<BankInfo>;
                BankInfo obsBankInfo = list.Where(p => p.BankType == cbx.SelectedValue.ToString()).FirstOrDefault();
                if (obsBankInfo.CardNo.Length >= 4)
                {
                    if (obsBankInfo.BankType != "财付通")
                        lbUserBankAccount.Text = "****************" + obsBankInfo.CardNo.Substring(obsBankInfo.CardNo.Length - 4, 4);
                    else
                        lbUserBankAccount.Text = "****" + obsBankInfo.CardNo.Substring(obsBankInfo.CardNo.Length - 4, 4);
                }
                else
                    lbUserBankAccount.Text = obsBankInfo.CardNo;
                lbUserAccountName.Text = obsBankInfo.UserName.Substring(0, 1) + "**";
            }
        }

        private void cbx_bankType_in_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cbx = sender as ComboBox;
            if (cbx.Tag != null&&cbx.SelectedValue!=null)
            {
                List<CarrierBankInfo> list = cbx.Tag as List<CarrierBankInfo>;
                CarrierBankInfo info = list.Where(p => p.BankType == cbx.SelectedValue.ToString()).FirstOrDefault();
                lbAccountName.Text = info.AccountName;
                lbBankAccount.Text = info.AccountNum;
                lbUserId.Text = user.ID.ToString();
                invalidTime = DateTime.Now.AddMinutes(5.0);
                timerShowInvalidTime.Start();
            }
            if (cbx.SelectedValue != null)
            {
                if (cbx.SelectedValue.ToString().Trim() == "财付通")
                {
                    lnk_cft.Visibility = Visibility.Visible;
                    lnk_gh.Visibility = Visibility.Collapsed;
                }
                else
                {
                    lnk_cft.Visibility = Visibility.Collapsed;
                    lnk_gh.Visibility = Visibility.Visible;
                }
            }
        }
    }
}

